package com.hanliy.handler;

import com.hanliy.dto.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author hanyulin
 * @apiNote
 * @date 2021/12/12 19:44
 */
@RestControllerAdvice
public class CommonExceptionHandler {

    /**
     * 在日志输出的时候，可以打印出日志信息所在类
     */
    private Logger logger = LoggerFactory.getLogger(CommonExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public Result exception(Exception e) {
        Result result = new Result();
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) e;
            List<ObjectError> allErrors = methodArgumentNotValidException.getBindingResult().getAllErrors();
            ObjectError objectError = allErrors.get(0);
            result.fail(objectError.getDefaultMessage());
            return result;
        }
        if (e instanceof BindException) {
            BindException bindException = (BindException) e;
            BindingResult bindingResult = bindException.getBindingResult();
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            ObjectError objectError = allErrors.get(0);
            result.fail(objectError.getDefaultMessage());
            return result;
        }
        if (e instanceof RuntimeException) {
            result.fail(e.getMessage());
            return result;
        }
        return result.fail();
    }

}
